package com.globant.bugfixer;

import java.util.ArrayList;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import com.globant.bugfixer.*;
public abstract class GenericProductReplace extends JdbcDaoSupport {
	
	public GenericProductReplace(){}
	
	public void replaceProduct(int product_to_update,int product_to_delete){
		Report presentReport;
		//ArrayList<Report> collection_reports=this.getElementsFromReport(product_id);
		ArrayList<Report> collection_toReplace_reports=this.getElementsFromReport(product_to_delete);
		
		for(int i=0;i<collection_toReplace_reports.size();i++){
			Report report_to_replace=collection_toReplace_reports.get(i);
			if((presentReport=this.isCombinationPresent(report_to_replace,product_to_update))!=null){
				int new_counter=presentReport.getTraffic()+report_to_replace.getTraffic();
				this.updateReport(new_counter,presentReport);
				System.out.println("Updated:"+presentReport);
			}else{
				try{
					this.insertReport(report_to_replace,product_to_update);
					System.out.println("Inserted:"+report_to_replace);
				}catch(Exception e1){
					
				}
			}
			this.deleteReport(report_to_replace);
			System.out.println("-------------------------------------");
			System.out.println("");
		}
	}

	

	public abstract void deleteReport(Report report) ;

	public abstract void updateReport(int new_counter, Report presentReport);

	public abstract Report isCombinationPresent(Report report_to_replace,ArrayList<Report> collection_reports) ;
	
	public abstract Report isCombinationPresent(Report report_to_replace,int product_id) ;

	public abstract void insertReport(Report report_to_replace, int product_id);

	public abstract ArrayList<Report> getElementsFromReport(int product_id);
	
	public abstract ArrayList<Report> getReport(Report report);
	//------------------------------------
	public static void main(String[] args){
	    	    
	    ApplicationContext context               = new ClassPathXmlApplicationContext("Spring-Bug_Replace.xml");		
		Integer toUpdate=new Integer(args[0]);
		Integer toReplace=new Integer(args[1]);

		GenericProductReplace reports = (TrafficProductReplace) context.getBean("reportTraffic");
		reports.replaceProduct(toUpdate, toReplace);
		
		reports = (SessionProductReplace) context.getBean("reportSession");
		reports.replaceProduct(toUpdate, toReplace);
		
		reports = (QueryProductReplace) context.getBean("reportQuery");
		reports.replaceProduct(toUpdate, toReplace);
		System.out.println("Query Report Finished---------------------------");
		
		reports = (NoResultQueryReplace) context.getBean("reportNoQuery");
		reports.replaceProduct(toUpdate, toReplace);
		System.out.println("Query Report Finished---------------------------");

		reports = (WordProductReplace) context.getBean("reportWord");
		reports.replaceProduct(toUpdate, toReplace);
	}

}
